<?php

/**
 * @Author: wuchenge
 * @Date: 2020-11-30 16:47:21
 * @email: ligui0506@sina.com
 * @descript: 公共验证器
 */

namespace App\Requests;

use App\Exceptions\ApiHandler;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest as BaseFormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Symfony\Component\HttpKernel\Exception\HttpException;

class FormRequest extends BaseFormRequest
{
    /**
     * 验证场景
     *
     * @var string
     */
    public $scene = [];

    public function authorize()
    {
        return true;
    }

    // 自定义错误
    protected function failedValidation(Validator $validator)
    {
        if ($validator->errors()) {
            $code = current(current($validator->errors()->messages()));
            // $err_msgs = explode('|', $err_msg);
            // $code = isset($err_msgs[0])
            // ? (
            //     is_numeric($err_msgs[0])
            //     ? $err_msgs[0]
            //     : 1
            // )
            // : 100400;
            // $msg = isset($err_msgs[1]) ? $err_msgs[1] : '参数错误...';
            // throw new HttpResponseException(response()->json(
            //     ['error_code' => $code, 'message' => $msg, 'data' => null],
            //     200
            // ));
            throw new ApiHandler($code, '');
        }

        // parent::failedValidation($validator);
    }

    protected function createDefaultValidator(ValidationFactory $factory)
    {

        return $factory->make(
            $this->validationData(),
            $this->getSceneRules(),
            $this->messages(),
            $this->attributes()
        );
    }

    /**
     * 获取场景验证规则
     *
     * @return array
     */
    protected function getSceneRules()
    {
        return $this->handleScene($this->container->call([$this, 'rules']));
    }

    /***
     * 基于路由名称的场景验证
     *
     * @param array $rule
     * @return array
     */
    public function handleScene(array $rule)
    {

        $arr   = [];
        $scene = $this->scene[$this->getSceneName()] ?? [];
        foreach ($scene as $item) {
            if (isset($rule[$item])) {
                $arr[$item] = $rule[$item];
            }
        }

        return $arr ?: $rule;
    }

    /**
     * 获取场景名称
     *
     * @return string
     */
    public function getSceneName()
    {
        return $this->input('_scene', $this->route()->getName());
    }
}
